package extractorCode;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class boingText {

	private final static int INITIAL_BUF_SIZE = 65536;
	public static void main(String args[]) throws Exception
	{
	
		int count=0;
	
		BufferedWriter wr; 
		int fileCount=0;
		//Keep an year counter...
		int year=2007;
		for(int i=1;i<=9&&year<2012;i++)
		{	
		System.out.println("page"+i);	
		String page = (fetchPage("http://boingboing.net/"+year+"/10/page/"+i));
		//System.out.println(page);
		page= page.replaceAll(">\\s*<", "><");
		
		page = page.replaceAll("\t", "");
		page = page.replaceAll("\b", "");
		page = page.replaceAll("\r", "");
		page = page.replaceAll("\n", "");
		page = page.replaceAll("\r\n", "");
				
		
		
		Matcher fullText=Pattern.compile("<div id=\"post-\\d+\" class=\"post\">(.*?)</div>", Pattern.CASE_INSENSITIVE).matcher( page );
		//<a href="http://talkingpointsmemo.com/archives/2011/10/just_go_all_in.php#more" class="rbutton more">Read more</a>
		Matcher newsItem = Pattern.compile("</h2><p class=\"byline\">.*?</p>(.*?)<div class=\"shareMe\">", Pattern.CASE_INSENSITIVE).matcher( page );

	//	newsItem.find();

		
		
		
	while(fullText.find())
		{
	//	System.out.println(newsItem.group(1));
		
		String text = fullText.group(1);
		System.out.println(text);
		text = text.replaceAll("<p class=\"byline\">.*?</p>", "");  // this is done to remove the extra tags
        text = text.replaceAll("\\<.*?>","");
        text = text.replaceAll("[^\\p{ASCII}]", "");//System.out.println(text);
		wr = new BufferedWriter(new FileWriter("c:\\newData\\Boing\\October\\"+(fileCount++)+"-"+year+".txt"));
		wr.write(text);
		
		wr.close();
		//System.out.println(text);
		//wr.write("http://newsbusters.org"+newsItem.group(1)+"\n");
		}
		
		year++;
		
		}
		
		
	}
	
	private static String fetchPage(String urlString){
		StringBuilder buffer = new StringBuilder(INITIAL_BUF_SIZE);
		try {
			URL url = new URL( urlString );
			BufferedInputStream reader = new BufferedInputStream(url.openStream());
			int temp = reader.read();
			while(temp != -1){
				buffer.append((char)temp);
				temp = reader.read();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buffer.toString();
	}

	
	
	
}
